package com.rockcent.message.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.Banner;
import com.rockcent.mall.lib.domain.SysMessage;
import com.rockcent.mall.lib.domain.SysMessageUser;
import com.rockcent.mall.lib.domain.Template;
import com.rockcent.mall.lib.domain.enumclass.GiftPacketStatus;
import com.rockcent.mall.lib.domain.enumclass.SysMessageStatus;
import com.rockcent.mall.lib.domain.enumclass.SysMessageType;
import com.rockcent.mall.lib.domain.enumclass.TerminalType;
import com.rockcent.mall.lib.dto.BannerDto;
import com.rockcent.mall.lib.dto.SysMessageDto;
import com.rockcent.mall.lib.dto.TemplateDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.BannerRepository;
import com.rockcent.message.Routes;
import com.rockcent.service.AuthUserResourceSrv;
import com.rockcent.service.SysMessageSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 消息处理中心
 * Created by zhangjh on 2017/5/23.
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class SysMessageController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(SysMessageController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private SysMessageSrv sysMessageSrv;

    /**
     * @api {get} /v1/sys_message/info 消息详情
     * @apiGroup sys_message
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} id <code>必须参数</code> 消息Id
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 1,
     *     "type": "SYS",
     *     "content": "您的实名认证已通过，马上去发布产品吧！",
     *     "frontendUrl": "/business/product/index/selling",
     *     "backendUrl": "/mall/merchant/certify/update",
     *     "dateCreated":"2017-06-01 12:01:01"
     *   }
     * }
     */
    @RequestMapping(value = Routes.SYSMESSAGE_INFO, method = RequestMethod.GET)
    public JsonResult queryInfo(@RequestParam("id") Long id, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (null == id) {
                jsonResult.errorParam("ID不能为空", log);
                return;
            }
            SysMessageDto banner = sysMessageSrv.findOneByIdAndIsDeleteAndUserId(id, Whether.NO, userDto.id);
            jsonResult.data = banner;

        };
        return doing.go(request, log);

    }


    /**
     * @api {put} /v1/sys_message/delete 删除消息
     * @apiGroup sys_message
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} id <code>必须参数</code> 消息id
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.SYSMESSAGE_DELETE, method = RequestMethod.PUT)
    public JsonResult deleteInfo(@RequestBody SysMessageDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
//        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            Long id = dto.getId();
            if (null == id) {
                jsonResult.errorParam("ID不能为空", log);
                return;
            }
            SysMessageUser sysMessageUser = sysMessageSrv.findOneById(id, Whether.NO);
            if (sysMessageUser == null) {
                jsonResult.errorParam("没有相应消息", log);
                return;
            }
            sysMessageUser.setIsDelete(Whether.YES);
            sysMessageSrv.saveSysMessageUser(sysMessageUser);
        };
        return doing.go(request, log);
    }


    /**
     * @api {put} /v1/sys_message/read 标记消息为已读
     * @apiGroup sys_message
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} ids <code>必须参数</code> 消息id集合
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.SYSMESSAGE_READ, method = RequestMethod.PUT)
    public JsonResult updateInfo(@RequestBody SysMessageDto dto, HttpServletRequest request) {

        UserInfoDto userDto = userHelper.getSession(request);
//        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {

            List<Long> ids = dto.getIds();
            if (null == ids || ids.isEmpty()) {
                jsonResult.errorParam("消息id集合为空", log);
                return;
            }
            for (Long id : ids) {
                SysMessageUser sysMessageUser = sysMessageSrv.findOneById(id, Whether.NO);
                if (sysMessageUser == null) {
                    jsonResult.errorParam("没有相应消息", log);
                    return;
                }
                sysMessageUser.setStatus(SysMessageStatus.READED);
                sysMessageSrv.saveSysMessageUser(sysMessageUser);
            }


        };
        return doing.go(request, log);
    }



    /**
     * @api {get} /sys_message/page 消息分页
     * @apiGroup sys_message
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} type <code>可选参数</code> 消息类型:ALL("全部"),SYS("系统"),OP("运营"),FINANCE("财务")
     * @apiParam {String} status <code>可选参数</code> 消息状态:ALL("全部"),READED("已读"),UNREAD("未读")
     * @apiParam {String} terminalType <code>必选参数</code> 终端类型：WECHAT("微信端") ,IOS("苹果APP端"),ANDROID("安卓APP端"),BROWER("PC端") ,MERCHANT("MERCHANT"),MALL("MALL") ,WXAPP("小程序"),UNKNOWN("未知")
     * @apiParam {String} destinationTerminalId <code>必选参数</code> 平台ID/商户ID
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 每页记录数
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "data":[
     *             {
     *                  "id": 1,
     *                  "type": "SYS",
     *                  "content": "您的实名认证已通过，马上去发布产品吧！",
     *                  "frontendUrl": "/business/product/index/selling",
     *                  "backendUrl": "/mall/merchant/certify/update",
     *                  "dateCreated":"2017-06-01 12:01:01",
     *                  "status":"READED"
     *
     *             }
     *             ....
     *         ],
     *         "totalCount":17,
     *         "totalPage":4,
     *         "pageNo":1,
     *         "pageSize":5
     *     }
     * }
     * }
     */
    @RequestMapping(value = Routes.SYSMESSAGE_PAGE, method = RequestMethod.GET)
    public JsonResult listInfo(SysMessageDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);

        dto.setUserId(userDto.getId());
        RestDoing doing = jsonResult -> {

            if (dto == null) {
                jsonResult.errorParam("查询条件为空", log);
                return;
            }
            if(null == dto.getDestinationTerminalId()){
                jsonResult.errorParam("平台ID/商户ID为空", log);
                return;
            }

            if( dto.getType()== null || !EnumUtils.isValidEnum(SysMessageType.class, dto.getType())){
                jsonResult.errorParam("消息类型不正确", log);
                return;
            }

            if( dto.getStatus()!= null && !EnumUtils.isValidEnum(SysMessageStatus.class, dto.getStatus())){
                jsonResult.errorParam("消息状态不正确", log);
                return;
            }
            if( dto.getTerminalType()== null || !EnumUtils.isValidEnum(TerminalType.class, dto.getTerminalType())){
                jsonResult.errorParam("终端类型不正确", log);
                return;
            }
            PageResult<SysMessageDto> pageResult = sysMessageSrv.page(dto,this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.SYSMESSAGE_PAGE);
            jsonResult.data = pageResult;

        };
        return doing.go(request, log);
    }

}
